package com.dy.controller;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dy.common.R;
import com.dy.common.RedisConstonts;
import com.dy.entity.User;
import com.dy.service.UserService;
import com.dy.utils.HttpClientUtil;
import com.dy.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private StringRedisTemplate stringRedis;

    @Autowired
    private UserService userService;


    /**
     * @Author dy
     * @Description: 用户登录获取验证码
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //HttpClientUtil.phoneNote();
        String phone = user.getPhone();
        if(StringUtils.isBlank(phone)){
            //手机号异常 手机号为空
            return R.error("短信发送失败,请输入手机号");
        }
        //获取手机号发送的验证码次数
        String count = stringRedis.opsForValue().get(RedisConstonts.CODE_NUM + phone);
        if(StringUtils.isNotBlank(count) && Integer.parseInt(count) >= 5){
            //短信次数异常
            return R.error("验证码获取过多，请在一小时后重试。");
        }

        //发送短信 获取四位 验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //验证码 已手机号为key 存入redis
        stringRedis.opsForValue().set(RedisConstonts.USER_CODE + phone,code,3, TimeUnit.MINUTES);
        //给手机号 添加防刷短信机制
        /*Long increment = stringRedis.opsForValue().increment(RedisConstonts.CODE_NUM + phone, 1L);
        log.info("次数：{}",increment);
        if(increment == 1){
            stringRedis.expire(RedisConstonts.CODE_NUM + phone,1,TimeUnit.HOURS);
        }*/

        log.info("验证码：{}",code);
        return R.success("短信发送成功。");
    }

    @Transactional
    @PostMapping("/login")
    public R<User> login(@RequestBody HashMap map , HttpSession session ){
        //获取获取手机号
        String phone = map.get("phone").toString();
        //获取提交的验证码
        String code = map.get("code").toString();

        //从redis 中获取保存的验证码
        String code1 = stringRedis.opsForValue().get(RedisConstonts.USER_CODE + phone);
        if(StringUtils.isNotBlank(code1) && code1.equals(code)){
            //验证码 一致
            //根据手机号查询数据库 判断是否是新用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User one = userService.getOne(queryWrapper);
            if(one == null){
                //新用户
                one = new User()
                        .setPhone(phone)
                        .setName("XRLX"+UUID.randomUUID().toString(true))
                        //默认头像
                        .setAvatar("Blog-Img/02d0c3efd38c4f1c952c9ee24f17aaf5.png")
                        .setUpdateTime(LocalDateTime.now())
                        .setCreateTime(LocalDateTime.now());
                userService.save(one);
                //将用户ID 存入session
                session.setAttribute("user",one.getId());
                return R.success(one);
            }
            //判断用户状态是否被停用
            if(one.getStatus() == 1){
                //将用户ID 存入session
                session.setAttribute("user",one.getId());
                return R.success(one);
            }
            // 用户已被停用
            return R.error("账号已被停用。");
        }

        //验证码 不一致 或者 手机号不正确
        return R.error("登陆失败。");
    }

}
